/*
 * Copyright (C) 2014 Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.bambole.facade;

import com.googlecode.bambole.domain.Configuration;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 */
@Stateless
public class ConfigurationFacade extends AbstractFacade<Configuration> {

    @PersistenceContext(unitName = "BambolePU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ConfigurationFacade() {
        super(Configuration.class);
    }

    public List findEnabled() {
        try {
            Query query = em.createNamedQuery("Configuration.findEnabled");

            return query.getResultList();
        } catch (NoResultException nre) {
            Logger.getAnonymousLogger().log(Level.INFO, "Configuration not found: {0}", nre.getMessage());

            return null;
        }
    }

    public Configuration findByName(String name) {
        try {
            Query query = em.createNamedQuery("Configuration.findByName").setParameter("name", name);

            return (Configuration) query.getSingleResult();
        } catch (NoResultException nre) {
            Logger.getAnonymousLogger().log(Level.INFO, "Configuration not found: {0}", nre.getMessage());

            return null;
        }
    }

    public boolean isNameUnique(String name, int id) {

        List<Configuration> configurationList;

        Query query = em.createNamedQuery("Configuration.findByName").setParameter("name", name);
        configurationList = query.getResultList();

        return configurationList.isEmpty() || (configurationList.size() == 1 && configurationList.get(0).getId() == id);
    }

}
